package com.android.webttest.View;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.android.webttest.R;
import com.android.webttest.View.FrameLayout.CommentBottomSheet;
import com.android.webttest.ViewModel.GoodViewModel;
import com.android.webttest.ViewModel.MainViewModel;
import com.android.webttest.databinding.ActivityGoodClickDetailBinding;
import com.android.webttest.model.GoodAllInfo;
import com.android.webttest.model.User;
import com.android.webttest.model.tableModel.GoodLike;
import com.android.webttest.utils.RoomDBTools;
import com.android.webttest.utils.StatusBarUtil;
import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.ui.PlayerView;

import java.util.concurrent.atomic.AtomicReference;

import com.google.android.exoplayer2.ui.StyledPlayerView;

public class GoodClickDetail extends AppCompatActivity {

    private Integer goodId;

    private String categoryName;


    private ImageView imageView;

    private StyledPlayerView videoView;

    private ImageButton backButton;


    private ImageButton goodComment;
    private ImageButton goodLikes;
    private ImageButton goodFavorite;
    private ImageButton goodShare;

    private TextView originalPrice;

    private User user;

    private MainViewModel mainViewModel;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EdgeToEdge.enable(this);
        ActivityGoodClickDetailBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_good_click_detail);

        StatusBarUtil.setImmersiveStatusBarR(this);

        backButton = findViewById(R.id.icon_search_back);
        goodComment = findViewById(R.id.good_comment);
        goodLikes = findViewById(R.id.good_likes);
        goodFavorite = findViewById(R.id.good_favorite);
        goodShare = findViewById(R.id.good_share);
        originalPrice = findViewById(R.id.original_price);

        // 获取 Intent 数据
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("goodId") && intent.hasExtra("categoryName")) {
            goodId = intent.getIntExtra("goodId", -1);
            categoryName = intent.getStringExtra("categoryName");
        }



        GoodViewModel goodViewModel = new ViewModelProvider(this).get(GoodViewModel.class);
        if (goodId != -1) {
            //开始请求goodAllInfo
            goodViewModel.fetchGoodAllInfo(goodId);
            AtomicReference<GoodAllInfo> goodAllInfo = new AtomicReference<>(new GoodAllInfo());
            goodViewModel.getGoodAllInfoLiveData().observe(this, goodAllInfoObserve -> {
                if(goodAllInfoObserve != null){
                    if(goodAllInfoObserve.getGoodCommentsProList()!=null){
                        goodComment.setOnClickListener(v -> {
                            CommentBottomSheet commentSheet = new CommentBottomSheet(goodAllInfoObserve.getGoodCommentsProList());
                            commentSheet.setOnCommentSubmitListener((comment) -> {
                                // 处理用户输入的评论内容
                                Log.d("Comment", "用户评论：" + comment);
                                // TODO: 提交到服务器或本地数据库
                            });
                            commentSheet.show(getSupportFragmentManager(), "CommentBottomSheet");
                        });
                    }

                    goodLikes.setOnClickListener(v -> {
                        if(goodAllInfoObserve.getGoodLike() == null){
                            goodAllInfoObserve.setGoodLike(new com.android.webttest.model.GoodLike());
                            goodLikes.setImageResource(R.drawable.icon_like_true);
                        }else{
                            goodLikes.setImageResource(R.drawable.icon_like);
                            goodAllInfoObserve.setGoodLike(null);
                        }
                    });

                    goodFavorite.setOnClickListener(v->{
                        if(goodAllInfoObserve.getGoodFavorite() == null){
                            goodAllInfoObserve.setGoodFavorite(new com.android.webttest.model.GoodFavorite());
                            goodFavorite.setImageResource(R.drawable.icon_favorite_true);
                        }
                        else {
                            goodFavorite.setImageResource(R.drawable.icon_favorite);
                            goodAllInfoObserve.setGoodFavorite(null);
                        }

                    });

                    goodShare.setOnClickListener(v->{
                        if(goodAllInfoObserve.getGoodShare() == null){
                            goodAllInfoObserve.setGoodShare(new com.android.webttest.model.GoodShare());
                            goodShare.setImageResource(R.drawable.icon_share_true);
                        }
                        else{
                            goodShare.setImageResource(R.drawable.icon_share);
                            goodAllInfoObserve.setGoodShare(null);
                        }
                    });

                    // 去除 Content 中的首尾 <p> 标签
                    String content = goodAllInfoObserve.getGood().getContent();
                    if (content != null && content.startsWith("<p>") && content.endsWith("</p>")) {
                        content = content.substring(3, content.length() - 4);
                    }
                    goodAllInfoObserve.getGood().setContent(content);

                    if(goodAllInfoObserve.getGood().getPrice()>goodAllInfoObserve.getGoodDetailInfo().getSellingPrice()){
                        originalPrice.setPaintFlags(originalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                    }

                    binding.setGoodAllInfo(goodAllInfoObserve);
                    binding.setCategoryName(categoryName);
                    binding.executePendingBindings();
                    goodAllInfo.set(goodAllInfoObserve);

                    // 获取 VideoView 和 ImageView 控件
                    videoView = findViewById(R.id.video_view_url);
                    ExoPlayer exoPlayer = new ExoPlayer.Builder(this).build();
                    videoView.setPlayer(exoPlayer);
                    imageView = findViewById(R.id.good_image_url);

                    // 设置播放的视频
                    if (goodAllInfoObserve.getMediaBean() != null && goodAllInfoObserve.getMediaBean().getUrl() != null) {
                        String videoUrl = goodAllInfoObserve.getMediaBean().getUrl();
                        MediaItem mediaItem = MediaItem.fromUri(videoUrl);
                        exoPlayer.setMediaItem(mediaItem);
                        exoPlayer.prepare();
                        exoPlayer.play();

                        // 隐藏控制器
                        // 初始隐藏一次控制器
                        videoView.hideController();

                        // 允许用户点击视频后控制器显示
                        videoView.setControllerVisibilityListener((StyledPlayerView.ControllerVisibilityListener) visibility -> {
                            // 可选：在此添加日志观察控制器状态变化
                            // Log.d("VideoController", "Visibility: " + visibility);
                        });
                    }


                    // 使用 Glide 加载图片
                    String imageUrl = goodAllInfoObserve.getGood().getCoverImg();
                    if (imageUrl != null && !imageUrl.isEmpty()) {
                        Glide.with(this)
                                .load(imageUrl)
                                .into(imageView);
                    }

                    Log.d("GoodClickDetail", "Received goodAllInfo: " + (goodAllInfoObserve != null ? goodAllInfoObserve.toString() : "null"));
                }
            });

//            binding.executePendingBindings(); // 可选，强制立即刷新 UI

        }
        backButton.setOnClickListener(v -> {
            releasePlayer();
            finish();

        });

    }
    private void releasePlayer() {
        if (videoView != null) {
            ExoPlayer player = (ExoPlayer) videoView.getPlayer();
            if (player != null) {
                player.stop();
                player.release(); // 释放资源
            }
            videoView.setPlayer(null); // 解除绑定
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (videoView != null) {
            ExoPlayer player = (ExoPlayer) videoView.getPlayer();
            if (player != null) {
                player.pause(); // 暂停播放
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (videoView != null) {
            ExoPlayer player = (ExoPlayer) videoView.getPlayer();
            if (player != null) {
                player.play(); // 恢复播放
            }
        }
    }
}